import React, {
  forwardRef,
  useCallback,
  useContext,
  useImperativeHandle,
  useRef,
  useState,
} from 'react'
import { useAntdTable, useRequest } from 'ahooks'
import { Badge, Button, Popconfirm } from 'antd'
import { Link } from 'umi'
import FlowContext from '../../FlowContext'
import styles from './index.less'
import request from '@/utils/request'
import SlickTable from '@/components/SlickTable'
import Space from '@/components/Space'
import IconFont from '@/components/IconFont'
import { toPath } from '@/utils/router'

const VersionStateMap = {
  0: <Badge status="warning" text="未生效" />,
  1: <Badge status="success" text="生效中" />,
  2: <Badge status="error" text="失效" />,
}

function encode(params) {
  let encodeStr = ''
  Object.keys(params).forEach((key) => {
    encodeStr = `${encodeStr}&${key}=${params[key]}`
  })
  return encodeStr
}

function VersionPageTable(
  {
    element,
    elementIdKey,
    elementId,
    elementVersionId,
    routePrefix = element,
    params = {},
    onClickConfig,
    readOnly,
    onValidVersion,
    onFirstLoading,
    ...rest
  },
  ref,
) {
  const { state } = useContext(FlowContext)
  const { versionId: processVersionId } = state
  const [mask, setMask] = useState(false)
  const first = useRef(true)

  const [currentVersionId, setCurrentVersionId] = useState(elementVersionId)

  const getTableData = useCallback(
    ({ current, pageSize }) => {
      return request
        .post(`/${element}/pageVersions`, {
          data: {
            current,
            pageSize,
            [elementIdKey]: elementId,
          },
        })
        .then((data) => {
          // if (readOnly) {
          //   const list = data.list.filter(e => e.versionId === elementVersionId);
          //   return {
          //     list: list.length === 0 ? data.list : list,
          //     total: data.total,
          //   };
          // }
          if (first.current) {
            first.current = false
            onFirstLoading && onFirstLoading(data.list)
          }
          return data
        })
    },
    [element, elementId, elementIdKey, onFirstLoading],
  )

  const {
    tableProps: { pagination, loading: tableLoading, ...restTableProps },
    refresh,
  } = useAntdTable(getTableData, {
    defaultPageSize: 5,
    refreshDeps: [elementId],
  })

  useImperativeHandle(ref, () => ({
    refresh,
    setCurrentVersionId,
  }))

  /**
   * 失效版本
   */
  const invalidVersion = useCallback(
    (versionId) => {
      setMask(true)
      request
        .post(`/${element}/invalidVersion?versionId=${versionId}`)
        .then(() => refresh())
        .finally(() => setMask(false))
    },
    [element, refresh],
  )

  /**
   * 删除版本
   */
  const deleteVersion = useCallback(
    (versionId) => {
      setMask(true)
      request
        .post(`/${element}/deleteVersion?versionId=${versionId}`)
        .then(() => refresh())
        .finally(() => setMask(false))
    },
    [element, refresh],
  )

  /**
   * 生效版本
   */
  const validVersion = useCallback(
    (versionId) => {
      setMask(true)
      request
        .post(`/${element}/validVersion?${elementIdKey}=${elementId}&versionId=${versionId}`)
        .then(() => {
          setCurrentVersionId(versionId)
          onValidVersion(versionId)
          refresh()
        })
        .finally(() => setMask(false))
    },
    [element, elementId, elementIdKey, onValidVersion, refresh],
  )

  /**
   * 复制版本
   */
  const copyVersion = useCallback(
    (versionId) => {
      setMask(true)
      request
        .post(`/${element}/copyVersion?${elementIdKey}=${elementId}&versionId=${versionId}`)
        .then(() => refresh())
        .finally(() => setMask(false))
    },
    [element, elementId, elementIdKey, refresh],
  )

  /**
   * 新增版本
   */
  const { loading, run: createNewVersion } = useRequest(
    () => {
      setMask(true)
      request
        .post(
          `/${element}/createNewVersion?${elementIdKey}=${elementId}&processVersionId=${processVersionId}`,
        )
        .finally(() => setMask(false))
    },
    {
      manual: true,
      onSuccess: refresh,
    },
  )

  const columns = [
    {
      title: '版本号',
      dataIndex: 'versionNumber',
      align: 'right',
      render: (text, record) =>
        record.versionId === currentVersionId
          ? (
          <>
            <IconFont type="icon-valid" className="text-success" style={{ marginRight: 4 }} />
            {text}
          </>
            )
          : (
              text
            ),
    },
    {
      title: '版本状态',
      dataIndex: 'versionState',
      render: text => VersionStateMap[text],
    },
    {
      title: '版本操作',
      width: '180px',
      render: (_text, record) => {
        const { versionId, versionState, versionNumber } = record
        const showCopyBtn = versionState === 1 || versionState === 2
        const showValidBtn = versionState === 0 || versionState === 2
        const showDeleteBtn = versionState === 0 || versionState === 2
        const showInvalidBtn = versionState === 1
        const showConfigBtn = versionState === 0

        return (
          <Space divider="vertical">
            {showCopyBtn
              ? (
              <Button
                style={{ padding: 0 }}
                type="link"
                disabled={readOnly}
                onClick={() => copyVersion(versionId)}
              >
                复制
              </Button>
                )
              : null}
            {showValidBtn
              ? (
              <Button
                style={{ padding: 0 }}
                type="link"
                disabled={readOnly}
                className={readOnly ? '' : 'text-success'}
                onClick={() => validVersion(versionId)}
              >
                生效
              </Button>
                )
              : null}
            {showDeleteBtn
              ? (
              <Popconfirm
                title={`确定要删除版本【${versionNumber}】吗`}
                onConfirm={() => deleteVersion(versionId)}
              >
                <Button
                  style={{ padding: 0 }}
                  type="link"
                  disabled={readOnly}
                  className="text-danger"
                >
                  删除
                </Button>
              </Popconfirm>
                )
              : null}
            {showInvalidBtn
              ? (
              <Button
                style={{ padding: 0 }}
                type="link"
                disabled={readOnly}
                className={readOnly ? '' : 'text-warning'}
                onClick={() => invalidVersion(versionId)}
              >
                失效
              </Button>
                )
              : null}
            {showConfigBtn
              ? (
                  onClickConfig
                    ? (
                <Button
                  style={{ padding: 0 }}
                  type="link"
                  disabled={readOnly}
                  onClick={() => onClickConfig({ elementId, versionId, readOnly: false })}
                >
                  配置
                </Button>
                      )
                    : (
                <Link
                  disabled={readOnly}
                  to={toPath(`/${routePrefix}/${elementId}?versionId=${versionId}${encode(params)}`)}
                >
                  配置
                </Link>
                      )
                )
              : null}
            {onClickConfig
              ? (
              <Button
                style={{ padding: 0 }}
                type="link"
                onClick={() => onClickConfig({ elementId, versionId, readOnly: true })}
              >
                预览
              </Button>
                )
              : (
              <Link
                to={toPath(`/${routePrefix}/${elementId}?versionId=${versionId}&readOnly=true${encode(
                  params,
                )}`)}
              >
                预览
              </Link>
                )}
          </Space>
        )
      },
    },
  ]

  return (
    <SlickTable
      rowClassName={row => row.versionId === currentVersionId && styles.highlightVersion}
      className={styles.table}
      loading={tableLoading || mask}
      rowKey="versionId"
      columns={columns}
      data={{ pagination: { ...pagination, showQuickJumper: false } }}
      {...restTableProps}
      {...rest}
      extra={
        readOnly
          ? null
          : (
          <Button type="primary" loading={loading} onClick={createNewVersion}>
            新建版本
          </Button>
            )
      }
    />
  )
}

export default forwardRef(VersionPageTable)
